package com.ruoyi.common.utils;

import java.util.HashMap;
import java.util.Map;

import com.ruoyi.common.config.WxMiniProgramConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 微信小程序工具类
 */
@Component
public class WxMiniProgramUtils {

    private static final Logger log = LoggerFactory.getLogger(WxMiniProgramUtils.class);

    @Autowired
    private WxMiniProgramConfig wxMiniProgramConfig;

    private String appId;
    private String appSecret;
    private String accessToken;
    private long accessTokenExpireTime;  // 记录access_token的过期时间

    public boolean checkConfig() {
        if (StringUtils.isEmpty(appId) || StringUtils.isEmpty(appSecret)) {
            Map<String, String> configs = getWxMiniProgramConfig();
            if (configs != null && !configs.isEmpty()) {
                appId = configs.get("appId");
                appSecret = configs.get("appSecret");
            }
        }
        return StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(appSecret);
    }

    private Map<String, String> getWxMiniProgramConfig() {
        Map<String, String> configs = new HashMap<>();
        configs.put("appId", wxMiniProgramConfig.getAppId());
        configs.put("appSecret", wxMiniProgramConfig.getAppSecret());
        return configs;
    }

    /**
     * 获取access_token（并缓存）
     */
    public String getAccessToken() {
        try {
            long currentTime = System.currentTimeMillis();
            // 如果access_token已过期，重新获取
            if (accessToken == null || currentTime >= accessTokenExpireTime) {
                String url = "https://api.weixin.qq.com/cgi-bin/token";
                String param = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
                String result = HttpUtils.sendGet(url, param);

                if (StringUtils.isEmpty(result)) {
                    log.error("获取access_token失败，请求微信服务器返回为空");
                    return null;
                }

                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("errcode") && json.getIntValue("errcode") != 0) {
                    log.error("获取access_token失败，错误码：{}，错误信息：{}", json.getIntValue("errcode"), json.getString("errmsg"));
                    return null;
                }

                accessToken = json.getString("access_token");
                int expiresIn = json.getIntValue("expires_in");
                // 缓存access_token和过期时间
                accessTokenExpireTime = currentTime + (expiresIn - 60) * 1000;  // 提前60秒过期，保证token有效
            }

            return accessToken;
        } catch (Exception e) {
            log.error("获取access_token异常", e);
            return null;
        }
    }

    /**
     * 获取用户openid
     */
    public String getOpenid(String code) {
        try {
            if (!checkConfig()) {
                log.error("微信小程序配置错误");
                return null;
            }

            // 请求微信服务器获取openid
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            String param = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
            String result = HttpUtils.sendGet(url, param);

            if (StringUtils.isEmpty(result)) {
                log.error("获取openid失败，请求微信服务器返回为空");
                return null;
            }

            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("errcode") && json.getIntValue("errcode") != 0) {
                log.error("获取openid失败，错误码：{}，错误信息：{}", json.getIntValue("errcode"), json.getString("errmsg"));
                return null;
            }

            return json.getString("openid");
        } catch (Exception e) {
            log.error("获取openid异常", e);
            return null;
        }
    }

    /**
     * 获取小程序用户信息（昵称、头像等）
     */
    public Map<String, String> getUserProfile(String openid, String accessToken) {
        try {
            String url = "https://api.weixin.qq.com/sns/userinfo";
            String param = "access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
            String result = HttpUtils.sendGet(url, param);

            if (StringUtils.isEmpty(result)) {
                log.error("获取用户信息失败，微信服务器返回为空");
                return null;
            }

            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("errcode") && json.getIntValue("errcode") != 0) {
                log.error("获取用户信息失败，错误码：{}，错误信息：{}", json.getIntValue("errcode"), json.getString("errmsg"));
                return null;
            }

            // 提取昵称、头像等信息
            Map<String, String> userProfile = new HashMap<>();
            userProfile.put("nickname", json.getString("nickname"));
            userProfile.put("avatarUrl", json.getString("headimgurl")); // 头像
            return userProfile;
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return null;
        }
    }

    /**
     * 获取手机号
     */
    public String getPhoneNumber(String code) {
        try {
            String accessToken = getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                log.error("获取access_token失败");
                return null;
            }

            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            JSONObject param = new JSONObject();
            param.put("code", code);

            String result = HttpUtils.sendPost(url, param.toJSONString());
            if (StringUtils.isEmpty(result)) {
                log.error("获取手机号失败，请求微信服务器返回为空");
                return null;
            }

            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("errcode") && json.getIntValue("errcode") != 0) {
                log.error("获取手机号失败，错误码：{}，错误信息：{}", json.getIntValue("errcode"), json.getString("errmsg"));
                return null;
            }

            if (json.containsKey("phone_info") && json.getJSONObject("phone_info").containsKey("phoneNumber")) {
                return json.getJSONObject("phone_info").getString("phoneNumber");
            }

            log.error("获取手机号失败，响应数据异常：{}", json);
            return null;
        } catch (Exception e) {
            log.error("获取手机号异常", e);
            return null;
        }
    }
}
